package com.atsmart.app.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.DisplayMetrics;

public class BitmapUtils {

	public static Bitmap resize2(Bitmap bitmap, int w, int h) {
		return Bitmap.createScaledBitmap(bitmap, w, h, true);

	}

	public static Bitmap resize3(Bitmap bitmap, int maxHeight, int maxWidth) {
		if (bitmap == null) {
			throw new IllegalArgumentException("bitmap");
		}

		int height = bitmap.getHeight();
		int width = bitmap.getWidth();

		if ((maxHeight > 0 && height <= maxHeight)
				&& (maxWidth > 0 && width <= maxWidth)) {
			return bitmap;
		}

		int newHeight = height;
		int newWidth = width;

		float ratio;

		if (newHeight > maxHeight && maxHeight > 0) {
			ratio = (float) newWidth / (float) newHeight;
			newHeight = maxHeight;
			newWidth = Math.round(ratio * (float) newHeight);
		}

		if (newWidth > maxWidth && maxWidth > 0) {
			ratio = (float) newHeight / (float) newWidth;
			newWidth = maxWidth;
			newHeight = Math.round(ratio * (float) newWidth);
		}

		return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);

	}

	public static Bitmap resize(Bitmap bitmap, int maxHeight, int maxWidth) {
		if (bitmap == null) {
			throw new IllegalArgumentException("bitmap");
		}

		int height = bitmap.getHeight();
		int width = bitmap.getWidth();

		if ((maxHeight > 0 && height <= maxHeight)
				&& (maxWidth > 0 && width <= maxWidth)) {
			return bitmap;
		}

		int newHeight = height;
		int newWidth = width;

		float ratio;

		if (newHeight > maxHeight && maxHeight > 0) {
			ratio = (float) newWidth / (float) newHeight;
			newHeight = maxHeight;
			newWidth = Math.round(ratio * (float) newHeight);
		}

		if (newWidth > maxWidth && maxWidth > 0) {
			ratio = (float) newHeight / (float) newWidth;
			newWidth = maxWidth;
			newHeight = Math.round(ratio * (float) newWidth);
		}

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
	}

	public static Bitmap downloadPictureAsBitmap(String url) throws IOException {
		// quit after a minute
		final int timeout = 30000;

		if (url == null) {
			throw new IllegalArgumentException("url");
		}

		Bitmap image = null;
		InputStream stream = null;
		try {
			URL fetchUrl = new URL(url);
			URLConnection conn = (URLConnection) fetchUrl.openConnection();
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);

			stream = conn.getInputStream();
			image = BitmapFactory.decodeStream(stream);
		} catch (IOException ex) {
			android.util.Log.e(null, android.util.Log.getStackTraceString(ex));
			throw ex;
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (Exception e) {
					/* Not much we can do */
				}
			}
		}
		return image;
	}

	public static Bitmap getThumbnail(Bitmap bitmap, double sizeWidth) {
		Bitmap scaled = null;
		Bitmap imgBitmap = bitmap;

		if (imgBitmap != null) {
			int w = imgBitmap.getWidth();

			if (w == (int) sizeWidth) {
				scaled = imgBitmap;
			} else {
				int h = imgBitmap.getHeight();
				double ratio = sizeWidth / w;
				w = (int) sizeWidth;
				h = (int) (ratio * h);
				scaled = Bitmap.createScaledBitmap(imgBitmap, w, h, true);
			}

			// if((h<=(int)sizeWidth) && (w<=(int)sizeWidth))
			// {
			// scaled = imgBitmap;
			// }
			// else
			// {
			// if((w>h)&&(w>sizeWidth)){
			// double ratio = sizeWidth/w;
			// w=(int)sizeWidth;
			// h=(int)(ratio*h);
			// }
			// else if((h>w)&&(h>sizeWidth)){
			// double ratio = sizeWidth/h;
			// h=(int)sizeWidth;
			// w=(int)(ratio*w);
			// }
			//
			// scaled = Bitmap.createScaledBitmap(imgBitmap, w, h, true);
			// }
		}

		return scaled;
	}

	public static Bitmap rotate(Bitmap b, float degree, int size) {
		if (b == null)
			return null;
		Matrix m = new Matrix();
		m.setRotate(degree);
		int w = b.getWidth();
		int h = b.getHeight();
		int x = 0;
		int y = 0;
		if (w <= h) {
			y = (h - w) / 2;
			h = w;
		} else {
			x = (w - h) / 2;
			w = h;
		}
		Bitmap b2 = Bitmap.createBitmap(b, x, y, w, h, m, false);
		b.recycle();
		b = Bitmap.createScaledBitmap(b2, size, size, false);
		b2.recycle();
		return b;
	}

	// Convert the image URI to the file system path of the image file
	public static String getImagePathFromURI(Context thisContext, Uri imgUri) {

		// can post image
		String fileName = null;
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = thisContext.getContentResolver().query(imgUri, proj, // Which
																				// columns
																				// to
																				// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)

		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			if (column_index < cursor.getColumnCount())
				fileName = cursor.getString(column_index);
			cursor.close();
		}

		return fileName;
	}

	public static String getWebArg(String webArg, String tag) {
		if (webArg == null)
			return null;

		String[] strs = webArg.split("&");

		int idx = 0;
		String ctag = tag + "=";
		int size = ctag.length();

		for (int i = 0; i < strs.length; i++) {
			idx = strs[i].indexOf(ctag);

			if (idx > -1 && idx + size < strs[i].length()) {
				return strs[i].substring(idx + size);
			}
		}

		return null;
	}

	public static boolean hasInternetConnection(Context context) {
		if (context == null) {
			throw new IllegalArgumentException("context");
		}

		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());
	}

	public static boolean isValidEmail(String email) {
		Pattern p = Pattern
				.compile("[a-zA-Z0-9\\-_\\.]++@[a-zA-Z0-9\\-_]++(\\.[a-zA-Z\\-_]++)++");
		Matcher m = p.matcher(email);
		if (m.matches())
			return true;

		return false;
	}

	public static boolean isValidAccount(String account) {
		Pattern p = Pattern.compile("[a-zA-Z0-9\\-_\\.]++");
		Matcher m = p.matcher(account);
		if (m.matches())
			return true;

		return false;
	}

	public static boolean isValidName(String name) {
		Pattern p = Pattern.compile("[.\u4e00-\u9fa5\\w\\s]{1,20}");
		Matcher m = p.matcher(name);
		if (m.matches())
			return true;

		return false;
	}

	public static boolean isValidPhone(String phone) {
		return true;
		/*
		 * if(phone.length() != 11) return false; if(phone.startsWith("1")) {
		 * char c;
		 *
		 * for(int i = 1; i < phone.length(); i++) { c = phone.charAt(i); if(c <
		 * '0' || c > '9') return false; }
		 *
		 * return true; }
		 *
		 * return false;
		 */
	}

	public static boolean isValidPhone2(String phone) {

		if (phone.length() != 11)
			return false;
		if (phone.startsWith("1")) {
			char c;

			for (int i = 1; i < phone.length(); i++) {
				c = phone.charAt(i);
				if (c < '0' || c > '9')
					return false;
			}

			return true;
		}

		return false;
	}

	/*
	 * *
	 * Convert an int to an hex String and pad with 0's up to minLen.
	 */

	public static String getPaddedHex(int nr, int minLen) {
		String str = Integer.toHexString(nr);
		if (str != null) {
			while (str.length() < minLen) {
				str = "0" + str;
			}
		}
		return str;
	}

	/**
	 * Convert an int to String and pad with 0's up to minLen.
	 */
	public static String getPaddedInt(int nr, int minLen) {
		String str = Integer.toString(nr);
		if (str != null) {
			while (str.length() < minLen) {
				str = "0" + str;
			}
		}
		return str;
	}

	public static int getScaleDensity(Context cx) {
		int ret = 16;
		int[] size = new int[2];
		DisplayMetrics dm = new DisplayMetrics();
		dm = cx.getApplicationContext().getResources().getDisplayMetrics();

		// check if Large screen & Medium density

		size[0] = dm.widthPixels;
		size[1] = dm.heightPixels;
		if (size[0] > size[1]) {
			int temp = size[0];
			size[0] = size[1];
			size[1] = temp;
		}
		if (size[0] == 480 && (size[1] == 800 || size[1] == 854))// && density
																	// == 1.5 )
		{
			ret = 24;
		}

		return ret;
	}
}
